package com.harry.home.wordpicture.Activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.harry.home.wordpicture.Fragment.ClassFragment;
import com.harry.home.wordpicture.Fragment.HomeFragment;
import com.harry.home.wordpicture.Fragment.MyFragment;
import com.harry.home.wordpicture.R;
import com.harry.home.wordpicture.Fragment.SearchFragment;

import java.util.ArrayList;
import java.util.List;

//切换碎片显示不同的视图要用replace
public class MainActivity extends AppCompatActivity {
    private List<Fragment> mList;
    private RadioGroup rg;
    private FrameLayout fl;
    private int currentIndex = 0;
    private int previousIndex = 0;
    private List<View> mView;
    //静态添加也可以，替换视图时用replaceView（）；
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg = (RadioGroup) findViewById(R.id.rg);
        fl = (FrameLayout) findViewById(R.id.container);
        initFragment();
        showView(currentIndex,previousIndex);
        ((RadioButton)rg.getChildAt(currentIndex)).setChecked(true);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //？？？？？当存在该视图时，直接找ID，因为已经有checkedId所以不用再查找
                RadioButton rb = (RadioButton) group.findViewById(checkedId);
                currentIndex = group.indexOfChild(rb);
                showView(currentIndex,previousIndex);
                previousIndex = currentIndex;
            }
        });
    }
    public void showView(int currentIndex,int previousIndex){
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment sf = mList.get(currentIndex);
        Fragment hf = mList.get(previousIndex);
        if(!mList.get(currentIndex).isAdded()){
            ft.add(R.id.container,sf);
        }
        if(currentIndex == previousIndex){
            ft.show(sf).commit();
            return;
        }else{
            ft.hide(hf);
            ft.show(sf);
            ft.commit();
        }
    }
    public void initFragment(){
        mList = new ArrayList<Fragment>();
        ClassFragment classFragment = new ClassFragment();
        HomeFragment homeFragment = new HomeFragment();
        SearchFragment searchFragment = new SearchFragment();
        MyFragment myFragment = new MyFragment();
        mList.add(homeFragment);
        mList.add(searchFragment);
        mList.add(myFragment);
        mList.add(classFragment);
    }
}
